<template>
  <div class="question-ask-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>提出问题</h2>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <!-- 课程信息提示 -->
      <div v-if="route.query.courseTitle" class="course-info-tip">
        <el-alert
          :title="`您正在为课程《${decodeURIComponent(route.query.courseTitle as string)}》提问`"
          type="info"
          :closable="false"
          show-icon
        />
      </div>

      <el-form
        :model="questionForm"
        :rules="questionRules"
        ref="questionFormRef"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="questionForm.title"
            placeholder="请输入问题标题（最多50字）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="关联课程" prop="courseId">
          <el-select
            v-model="questionForm.courseId"
            placeholder="选择关联课程（可选）"
            clearable
            @change="onCourseChange"
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="questionForm.courseId"
          label="关联课时"
          prop="lessonId"
        >
          <el-select
            v-model="questionForm.lessonId"
            placeholder="选择关联课时或视频（可选）"
            clearable
          >
            <!-- 课时选项 -->
            <el-option-group label="课时">
              <el-option
                v-for="lesson in courseLessons"
                :key="lesson.id"
                :label="lesson.title"
                :value="lesson.id"
              />
            </el-option-group>

            <!-- 视频选项 -->
            <el-option-group label="课程视频" v-if="courseVideos.length > 0">
              <el-option
                v-for="video in courseVideos"
                :key="video.id"
                :label="video.title"
                :value="video.id"
              />
            </el-option-group>
          </el-select>
          <div v-if="courseLessons.length === 0 && courseVideos.length === 0 && questionForm.courseId" class="no-lessons-tip">
            <el-alert
              title="该课程暂无课时和视频信息，无法关联具体内容"
              type="info"
              :closable="false"
              show-icon
              size="small"
            />
          </div>
        </el-form-item>

        <el-form-item label="问题描述" prop="content">
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="10"
            placeholder="详细描述您的问题（最多500字）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitQuestion"
            :loading="submitLoading"
          >
            提交问题
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '../../utils/request'
import { sanitizeHtml } from '../../utils/xss'

// 路由
const route = useRoute()
const router = useRouter()

// 表单引用
const questionFormRef = ref()

// 数据
const questionForm = reactive({
  title: '',
  courseId: null,
  lessonId: null,
  content: ''
})

const courses = ref([])
const courseLessons = ref([])
const courseVideos = ref([])  // 添加课程视频数据
const submitLoading = ref(false)

// 表单验证规则
const questionRules = {
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { max: 50, message: '标题长度不能超过50字', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { max: 500, message: '描述长度不能超过500字', trigger: 'blur' }
  ]
}

// 获取课程列表
const fetchCourses = async () => {
  try {
    const response = await request.get('/api/study/courses/published', {
      params: {
        page: 0,
        size: 100
      }
    })
    courses.value = response.data.content
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 根据课程ID获取课时列表和课程视频
const fetchLessonsByCourse = async (courseId: number) => {
  if (!courseId) {
    courseLessons.value = []
    courseVideos.value = []
    return
  }

  try {
    // 先获取课程模块
    const modulesResponse = await request.get(`/api/study/courses/${courseId}/modules`)
    const modules = modulesResponse.data

    // 获取所有模块的课时
    courseLessons.value = []
    if (modules && modules.length > 0) {
      for (const module of modules) {
        const lessonsResponse = await request.get(`/api/study/courses/modules/${module.id}/lessons`)
        courseLessons.value = [...courseLessons.value, ...lessonsResponse.data]
      }
    }

    // 获取课程视频
    courseVideos.value = []
    try {
      const videosResponse = await request.get(`/api/study/videos/course/${courseId}`)
      if (videosResponse.data.success && videosResponse.data.videos) {
        courseVideos.value = videosResponse.data.videos
      }
    } catch (videoError) {
      // 如果获取视频失败，不影响主流程
      console.warn('获取课程视频失败:', videoError)
    }

    // 如果没有模块和视频，给出提示
    if ((!modules || modules.length === 0) && courseVideos.value.length === 0) {
      ElMessage.warning('该课程暂无模块和视频信息')
    } else if (courseLessons.value.length === 0 && courseVideos.value.length === 0) {
      ElMessage.warning('该课程暂无课时和视频信息')
    }
  } catch (error: any) {
    console.error('获取课时列表失败:', error)
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请先登录')
    } else {
      ElMessage.error('获取课时列表失败')
    }
    courseLessons.value = []
    courseVideos.value = []
  }
}

// 课程选择变化
const onCourseChange = (courseId: number) => {
  questionForm.lessonId = null
  fetchLessonsByCourse(courseId)
}

// 提交问题
const submitQuestion = async () => {
  if (!questionFormRef.value) return

  await questionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造请求数据
        const requestData: any = {
          title: sanitizeHtml(questionForm.title),
          content: sanitizeHtml(questionForm.content)
        }

        // 只有当courseId存在时才添加到请求数据中
        if (questionForm.courseId) {
          requestData.courseId = questionForm.courseId
        }

        // 只有当lessonId存在时才添加到请求数据中
        if (questionForm.lessonId) {
          requestData.lessonId = questionForm.lessonId
        }

        const response = await request.post('/api/study/questions', requestData)
        ElMessage.success('问题提交成功')

        // 返回问题列表页面
        if (questionForm.courseId) {
          router.push(`/study/courses/${questionForm.courseId}`)
        } else {
          router.push('/study/questions')
        }
      } catch (error: any) {
        console.error('问题提交失败:', error)
        if (error.response) {
          console.error('Error response:', error.response)
          ElMessage.error(`问题提交失败: ${error.response.status} - ${error.response.statusText}`)
        } else {
          ElMessage.error('问题提交失败')
        }
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  questionForm.title = ''
  questionForm.courseId = null
  questionForm.lessonId = null
  questionForm.content = ''
  courseLessons.value = []
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCourses()

  // 如果URL中有courseId参数，自动设置
  const courseId = route.query.courseId
  if (courseId) {
    questionForm.courseId = Number(courseId)
    fetchLessonsByCourse(Number(courseId))
  }

  // 如果URL中有lessonId参数，自动设置
  const lessonId = route.query.lessonId
  if (lessonId) {
    questionForm.lessonId = Number(lessonId)
  }

  // 如果URL中有courseTitle参数，显示在页面标题中
  const courseTitle = route.query.courseTitle
  if (courseTitle) {
    document.title = `提问 - ${decodeURIComponent(courseTitle as string)}`
  }
})
</script>

<style scoped>
.question-ask-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.course-info-tip {
  margin-bottom: 20px;
}

.no-lessons-tip {
  margin-top: 10px;
}
</style>
